<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\ToolkitUserModel;
use share\exception\ApiException;
use share\service\BaseModelService;
use share\utils\Helper;

class ToolkitUserService extends BaseModelService
{

    public static function getModel()
    {
        return new ToolkitUserModel;
    }

    /**
     * 编辑条目 新增或者修改
     */
    public static function edit($info)
    {
        $id = $info['id'];
        unset($info['id']);
        if ($id == 0) {
            self::addToolkitUser($info);
        } else {
            self::updateToolkitUser($id, $info);
        }
        //TODO add code here after data change
        return $info;
    }

    /**
     * 新增条目
     */
    public static function addToolkitUser($info)
    {
        $salt = Helper::getRandomStr(8);
        $pass = self::makePasswordData($info['pass'],$salt);
        $info['salt'] = $salt;
        $info['pass'] = $pass;
        self::add($info);
    }

    /**
     * 修改条目
     */
    public static function updateToolkitUser($id, $info)
    {
        $origin  = self::getBase($id);
        if (empty($origin)) {
            throw new ApiException("origin data is not exists", ErrnoPlus::COMMON_INVALID_INPUT);
        }
        if(isset($info['account'])){ //账号不许改
            unset($info['account']);
        }
        if(!empty($info['pass'])){
            $salt = Helper::getRandomStr(8);
            $pass = self::makePasswordData($info['pass'],$salt);
            $info['salt'] = $salt;
            $info['pass'] = $pass;
        }
        self::update($id, $info);
    }


    public static function makePasswordData($pass,$salt){
        return md5(md5($salt).$pass);
    }

    public static function checkUser($account,$pass){
        $user = self::getByFilter([
            'account' => $account,
        ]);
        if(empty($user)){
            return null;
        }
        $sign = self::makePasswordData($pass,$user['salt']);
        if($sign === $user['pass']){
            unset($user['salt']);
            unset($user['pass']);
            return $user;
        }
        return null;
    }

    // /**
    //  * 删除条目
    //  */
    // public static function delById($id)
    // {
    //     $origin = self::getBase($id);
    //     if (empty($origin)) {
    //         return;
    //     }
    //     $res = self::del($id);
    //     return $res;
    // }

    /**
     * 页面查询条件
     */
    public static function buildCondition($filter)
    {
        $res = [];
        if (isset($filter['account']) && !empty($filter['account'])) {
            $res['account'] = ['like', '%' . $filter['account'] . '%'];
        }
        return $res;
    }
}
